//
//  AdressListController.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/30.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import LJContactManager

class AdressListController: BaseViewController {
    
    var dataModels : [AddressInfoModel]?


    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "地址管理"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "新建", style: .plain, target: self, action: #selector(pushAdressAdd))
        
        groupTableView.rowHeight = UITableViewAutomaticDimension
        
        groupTableView.estimatedRowHeight = 100
        
        
        groupTableView.register(UINib(nibName: StringFromClass(classType: AdressListCell.self), bundle: nil), forCellReuseIdentifier: AdressListCell.identifer())
        
        
        weak var weakSelf = self
        groupTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadAdressListData()
            
        }
        
        groupTableView.mj_header.beginRefreshing()
        
        
        // Do any additional setup after loading the view.
    }
    
    func pushAdressAdd() {
        
        let temp = AddAdressController()
        
        temp.block = {() ->() in
            
            
            self.loadAdressListData()
            
        }
        
        navigationController?.pushViewController(temp, animated: true)
        
    }

  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}



extension AdressListController{
    
    
    
    func loadAdressListData() {
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_address&a=address_list", parameters: nil) { [weak self] (responseObject, error) in
            
            if error == nil{
                
                self?.dataModels = [AddressInfoModel]()
                
                for dic in responseObject!["datas"]!["address_list"] as! [[String : AnyObject]]{
                    
                    self?.dataModels?.append(AddressInfoModel(dic: dic))
                    
                }
                
                if self!.dataModels!.count == 0{
                    
                    self?.showLogoView(text: "您还没有收货地址哦!")
                    
                    self?.dataModels = nil
                    
                }else{
                    
                    self?.dissmissLogoView()
                    
                    self?.dataSort()
                    
                }
                
                
                
                self!.groupTableView.mj_header.endRefreshing()
                
                self!.groupTableView.reloadData()
                
                
            }else{
                
                
                self!.groupTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
                
                
            }
            
        }
        
        
        
    }
    
    
    
    func dataSort() {
        
        var temp : AddressInfoModel? = nil
        
        var idex = 0
        
        for (index,item) in dataModels!.enumerated() {
            
            if item.is_default == "1" {
                temp = item
                idex = index
            }
        }
        
        
        
        if temp != nil {
            dataModels?.remove(at: idex)
            dataModels?.insert(temp!, at: 0)
        }
        
        
    }
    
    
    
}




extension AdressListController{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        return dataModels!.count
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if dataModels == nil {
            return 0
        }
        
        
        return 1
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let tableCell : AdressListCell =  tableView.dequeueReusableCell(withIdentifier: AdressListCell.identifer()) as! AdressListCell
        
        let temp =  dataModels![indexPath.section]
        
        temp.index = indexPath.section
        
        tableCell.model = temp
        
        tableCell.delegate = self
        
        return tableCell
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            return 0.00001
        }
        
        
        return 10
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.00001
    }
    
    
    
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    
    
    
    
    
}


extension AdressListController :AdressListCellDelegate{

    func setupDefualAdressBtnDidTap(btn: UIButton, model: AddressInfoModel) {
        
        
        for item in dataModels! {
            item.is_default = "0"
        }
        
        model.is_default = "1"
        
        groupTableView.reloadData()
        
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["address_id"] = "\(model.address_id)" as AnyObject

        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_address&a=set_default", parameters: parmeter) {(responseObject, error) in
            
            
               }
        
    }
    
    
    func deleAdressBtnDidTap(model: AddressInfoModel) {
        
        
            let tempVC = UIAlertController(title: nil, message: "确定删除地址?", preferredStyle: .alert)
            
            let action1 = UIAlertAction(title: "确定", style: .destructive) { (action) in
                
                self.deleAdress(model: model)
                
            }
            
            
            
            let action2 = UIAlertAction(title: "取消", style: .default) { (action) in
                
                
            }
            
            tempVC.addAction(action2)
            tempVC.addAction(action1)
            
            present(tempVC, animated: true, completion: nil)
            
            
  
        
        
    }
    
    
    
    func deleAdress(model: AddressInfoModel){
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["address_id"] = "\(model.address_id)" as AnyObject
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=member_address&a=address_del", parameters: parmeter) {[weak self] (responseObject, error) in
            
            if error == nil{
                
                self?.dataModels?.remove(at: model.index)
                
                if self?.dataModels!.count == 0{
                    
                    
                    self?.showLogoView(text: "您还没有收货地址哦!")
                    
                    
                }else{
                    
                    self?.dissmissLogoView()
                    
                    
                }
                
                self?.groupTableView.reloadData()
                
            }else{
                
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
        }

        
    }


}
